import { ISubscribe } from "./Subscribe"
export class Broker {
    private topics = new Map<string, ISubscribe[]>()
    constructor() {
        
    }
    subscribe(topic: string, callback: ISubscribe): void {
        let arr = this.topics.get(topic)
        if (!arr) {
            arr = []
        }
        if (arr.indexOf(callback) === -1) {
            arr.push(callback)
        }
        this.topics.set(topic, arr)
    }
    unsubscribe(topic:string,callback:ISubscribe):void{
        const arr = this.topics.get(topic)
        if (arr) {
            const index = arr.indexOf(callback)
            if (index !== -1) {
                arr.splice(index, 1)
                this.topics.set(topic, arr)
                return
            }
        }
    }
/**
 * 发布指定主题的消息。
 * @param topic 要发布的主题名称。
*/    publish(topic: string,msg:any) {
        const arr = this.topics.get(topic)
        if (arr) {
            arr.forEach((sub) => {
                sub.receive(msg)
            })
        }
    }
}